#!/usr/bin/env python
# -*- coding:utf-8 -*-

from flask_restful import Resource, reqparse
from flask import Flask, request, jsonify
from service.resourceService import ResourceService
from utils import commons
from utils.response_code import RET
from app import db

class ResourceOtherResource(Resource):
    @classmethod
    def upload_resource(cls):

        parser = reqparse.RequestParser()
        parser.add_argument('user_id', location='form', required=True, help='user_id参数类型不正确或缺失')
        # parser.add_argument('resource_id', location='form', required=False, help='resource_id参数类型不正确或缺失')
        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)

        kwargs['file'] = request.files['file']
        # 调用添加或更新资源方法
        res = ResourceService.add_or_update_resource(**kwargs)

        return jsonify(code=res['code'], message=res['message'], data=res['data'])

    @classmethod
    def look_resource(cls):
        """
        查看资源接口，获取所有资源或单个资源的详情
        :return: 返回资源的列表或单个资源的详细信息
        """
        # 解析请求参数
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', location='args', required=False, help='user_id 参数类型不正确或缺失')
        parser.add_argument('resource_id', location='args', required=False, help='resource_id 参数类型不正确或缺失')
        parser.add_argument('page', location='args', type=int, default=1, help='分页的页码，默认为1')
        parser.add_argument('page_size', location='args', type=int, default=10, help='每页数据量，默认为10')
        parser.add_argument('resource_type', location='args', type=int, help='资源类型，用于过滤图片、视频等')
        parser.add_argument('is_deleted', location='args', type=int, default=0, help='是否已删除，默认为0（未删除）')

        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)  # 去除空值
        # user_id 校验
        if 'user_id' in kwargs and not kwargs['user_id']:
            return jsonify(code=RET.PARAMERR, message="缺少 user_id 参数", data={})
        # 调用 ResourceService 获取资源列表
        res = ResourceService.get_all_resources(**kwargs)
        return jsonify(code=res['code'], message=res['message'], data=res['data'])

    @classmethod
    def get_id(cls):
        # 解析请求参数
        parser = reqparse.RequestParser()
        parser.add_argument(
            'account',
            location='args',
            required=True,
            help='account 参数类型不正确或缺失'
        )
        kwargs = parser.parse_args()

        # 调用服务层逻辑处理请求
        try:
            res = ResourceService.get_user_id(**kwargs)
            return jsonify(code=res['code'], message=res['message'], data=res['data'])
        except Exception as e:
            # 捕获服务层抛出的任何异常
            return jsonify(code=500, message=f"服务器内部错误: {str(e)}", data=None)

